package onion.mqtt.server.manager;

import onion.mqtt.server.store.SessionStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Mr, Lu
 * @developmentTeam 浙江允泽信息科技有限公司
 * @createTime 2023/12/12
 */
public final class SessionManager {
    static final Logger log = LoggerFactory.getLogger(SessionManager.class);
    private volatile static SessionManager INSTANCE;

    private final Map<String, SessionStore> sessionMap = new ConcurrentHashMap<>();

    private SessionManager() {}

    /**
     * 单例模式，获取对象
     * @return
     */
    public static SessionManager getInstance() {
        if (INSTANCE == null) {
            synchronized (SessionManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new SessionManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 添加session对象
     *
     * @param sessionStore
     */
    public synchronized void addSession(SessionStore sessionStore) {
        sessionMap.put(sessionStore.getClientId(), sessionStore);
        log.debug("client online, clientId: {}, total: {}", sessionStore.getClientId(), sessionMap.size());
    }

    /**
     * 判断是否存在session对象
     * @param clientId
     * @return
     */
    public boolean hasSession(String clientId) {
        return sessionMap.containsKey(clientId);
    }

    /**
     * 获取session对象
     *
     * @param clientId
     * @return
     */
    public SessionStore getSession(String clientId) {
        if (!sessionMap.containsKey(clientId)) {
            return null;
        }
        return sessionMap.get(clientId);
    }

    /**
     * 移除session对象
     *
     * @param clientId
     */
    public synchronized void removeSession(String clientId) {
        if (!sessionMap.containsKey(clientId)) {
            return;
        }
        sessionMap.remove(clientId);
        log.debug("client offline, clientId: {}, total: {}", clientId, sessionMap.size());
    }
}
